package com.chinasoft.maysham.manager.service.cluster.impl;

import com.chinasoft.maysham.manager.exception.BizException;
import com.chinasoft.maysham.manager.model.Cluster;
import com.chinasoft.maysham.manager.repo.ClusterRepo;
import com.chinasoft.maysham.manager.request.ClusterCreateReq;
import com.chinasoft.maysham.manager.service.DockerHelper;
import com.chinasoft.maysham.manager.service.cluster.ClusterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ClusterServiceImpl implements ClusterService {

    @Resource
    private ClusterRepo clusterRepo;

    @Resource
    private DockerHelper dockerHelper;

    @Override
    public Cluster create(ClusterCreateReq createReq) {
        if (clusterRepo.existByNameAndTag(createReq.getName(), createReq.getTag())) {
            throw new BizException("name duplicated");
        }
        Cluster cluster = new Cluster();
        cluster.setName(createReq.getName());
        cluster.setDescription(createReq.getDescription());
        cluster.setType(createReq.getType());
        cluster.setHost(createReq.getHost());
        cluster.setPort(createReq.getPort());
        cluster.setTag(createReq.getTag());
        if (!checkHealth(cluster)) {
            throw new BizException("not health cluster");
        }
        return clusterRepo.save(cluster);
    }

    @Override
    public boolean checkHealth(Cluster cluster) {
        String url = buildUrl(cluster);
        try {
            Map<String, Object> objectMap = dockerHelper.info(url);
            return true;
        } catch (RestClientException e) {
            return false;
        }
    }

    private String buildUrl(Cluster cluster) {
        return "http://" + cluster.getHost() + ":" + cluster.getPort();
    }

    @Override
    public boolean delete(String clusterId) {
        return clusterRepo.deleteById(clusterId, Cluster.class);
    }

    @Override
    public List<Cluster> list(int page, int size) {
        return clusterRepo.find(Criteria.where("deleted").is(false), PageRequest.of(page, size), Cluster.class);
    }
}
